package com.ciwong.epaper.modules.epaper.ui.newlistenspeak.shortcoversation.manager;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.PointF;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.LinearSmoothScroller;
import android.support.v7.widget.RecyclerView;
import android.util.DisplayMetrics;
import android.util.Log;

/**
 * date :2018/4/28
 * author: loco
 * description:  控制滑动速度的LinearLayoutManager
 * version:
 * email: lzh838330255@163.com
 */
public class ScrollSpeedLinearLayoutManger extends LinearLayoutManager {


    private boolean isScrollEnabled = true;
    private Context context;

    public ScrollSpeedLinearLayoutManger(Context context) {
        this(context, VERTICAL, false);
    }

    public ScrollSpeedLinearLayoutManger(Context context, int orientation, boolean reverseLayout) {
        super(context, orientation, reverseLayout);
        this.context = context;
    }


    @Override
    public void smoothScrollToPosition(RecyclerView recyclerView, RecyclerView.State state, int position) {
        Log.e("loco",
                "smoothScrollToPosition(ScrollSpeedLinearLayoutManger.java:62)");
        RecyclerView.SmoothScroller smoothScroller = new CenterSmoothScroller(recyclerView.getContext());
        smoothScroller.setTargetPosition(position);
        startSmoothScroll(smoothScroller);
    }

    private class CenterSmoothScroller extends LinearSmoothScroller {

        CenterSmoothScroller(Context context) {
            super(context);
        }

        @Nullable
        @Override
        public PointF computeScrollVectorForPosition(int targetPosition) {
            return ScrollSpeedLinearLayoutManger.this.computeScrollVectorForPosition(targetPosition);
        }

        @Override
        public int calculateDtToFit(int viewStart, int viewEnd, int boxStart, int boxEnd, int snapPreference) {
//            return (boxStart + (boxEnd - boxStart) /2) - (viewStart + (viewEnd - viewStart)/2);
            return (boxStart) - (viewStart);
        }

        protected float calculateSpeedPerPixel(DisplayMetrics displayMetrics) {

            return Resources.getSystem().getDisplayMetrics().density * 0.3f/displayMetrics.density;
        }

        @Override
        protected int getVerticalSnapPreference() {
            return SNAP_TO_START;
        }
    }

    public void setScrollEnabled(boolean flag) {
        this.isScrollEnabled = flag;
    }

    @Override
    public boolean canScrollVertically() {
        //Similarly you can customize "canScrollHorizontally()" for managing horizontal scroll
        return isScrollEnabled && super.canScrollVertically();
    }

}
